﻿using DevExpress.XtraEditors;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using B.MESUI.Login.Properties;
using Newtonsoft.Json.Linq;
using System.Net.Http;
using DevExpress.XtraGrid.Views.Grid;
using DevExpress.XtraGrid;

namespace B.MESUI.Login.BasicData_UI.Customer
{
    public partial class GetRelationForm : DevExpress.XtraEditors.XtraForm
    {
        private GetUserControl userControl;
        private string customerId;
        private int pageIndex = 1, pageSize = 10, totalCount = 0;

        /// <summary>
        /// 联系记录实体类
        /// </summary>
        public class RelationRecordDTO
        {
            public string id { get; set; }
            public DateTime relation_DateTime { get; set; }
            public DateTime next_RelationDateTime { get; set; }
            public string relation_Node { get; set; }
            public string customer_ID { get; set; }
        }

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="customerId">客户ID</param>
        public GetRelationForm(string customerId)
        {
            InitializeComponent();
            this.customerId = customerId;
            InitUI();
            _ = LoadData();
        }

        /// <summary>
        /// 初始化界面
        /// </summary>
        private void InitUI()
        {
            // 设置窗体大小
            this.Width = 1800;
            this.Height = 1000;
            this.StartPosition = FormStartPosition.CenterScreen;
            // 初始化用户控件
            userControl = new GetUserControl { Dock = DockStyle.Fill };
            this.Controls.Add(userControl);
            // 新增按钮居中放置
            var panelBtn = new FlowLayoutPanel { FlowDirection = FlowDirection.LeftToRight, Dock = DockStyle.Top, Height = 50, AutoSize = true, Padding = new Padding(0, 10, 0, 10) };
            var btnAdd = new SimpleButton { Text = "新增", Width = 90, Height = 40, Margin = new Padding(10, 0, 10, 0) };
            btnAdd.Click += (s, e) =>
            {
                var addForm = new AddRelationForm(customerId);
                addForm.RelationAdded += async () => { await LoadData(); };
                addForm.ShowDialog();
            };
            panelBtn.Controls.Add(btnAdd);
            this.Controls.Add(panelBtn);
            panelBtn.BringToFront();
            //把修改删除按钮都禁用
            userControl.btnDelete.Enabled = false;
            userControl.btnEdit.Enabled = false;
            userControl.btnExport.Enabled = false;
            userControl.btnQuery.Enabled = false;
            userControl.btnReset.Enabled = false;
            // 绑定事件
            userControl.btnQuery.Click += async (s, e) => { pageIndex = 1; await LoadData(); };
            userControl.btnReset.Click += async (s, e) =>
            {
                var qv = userControl.GetQueryValues();
                foreach (var k in qv.Keys.ToList())
                {
                    if (userControl.QueryControls[k] is DevExpress.XtraEditors.BaseEdit be)
                        be.EditValue = null;
                }
                pageIndex = 1;
                await LoadData();
            };
            // 分页按钮事件
            userControl.btnPrev.Click += async (s, e) => { if (pageIndex > 1) { pageIndex--; await LoadData(); } };
            userControl.btnNext.Click += async (s, e) => { if (pageIndex < GetTotalPages()) { pageIndex++; await LoadData(); } };
            userControl.btnFirst.Click += async (s, e) => { pageIndex = 1; await LoadData(); };
            userControl.btnLast.Click += async (s, e) => { pageIndex = GetTotalPages(); await LoadData(); };
            userControl.btnJump.Click += async (s, e) =>
            {
                int jumpPage;
                if (int.TryParse(userControl.txtJump.Text, out jumpPage))
                {
                    if (jumpPage >= 1 && jumpPage <= GetTotalPages())
                    {
                        pageIndex = jumpPage;
                        await LoadData();
                    }
                }
            };
        }

        private int GetTotalPages() => (int)Math.Ceiling((double)totalCount / pageSize);
        
        /// <summary>
        /// 加载联系记录数据
        /// </summary>
        private async Task LoadData()
        {
            string url = $"http://localhost:5198/api/Record/GetRelstion";
            var paramList = new List<string>
            {
                $"PageIndex={pageIndex}",
                $"PageSize={pageSize}",
                $"ID={customerId}"
            };
            url += "?" + string.Join("&", paramList);
            using (HttpClient client = new HttpClient())
            {
                try
                {
                    var resp = await client.GetAsync(url);
                    string json = await resp.Content.ReadAsStringAsync();
                    var jobj = JObject.Parse(json);
                    // 解析返回数据
                    totalCount = jobj["totalCount"]?.Value<int>() ?? 0;
                    var pageList = jobj["pageDatas"] as JArray;
                    var dataList = new List<RelationRecordDTO>();
                    if (pageList != null)
                    {
                        foreach (var item in pageList)
                        {
                            dataList.Add(new RelationRecordDTO
                            {
                                id = item["id"]?.ToString(),
                                relation_DateTime = item["relation_DateTime"] != null ?
                                    DateTime.Parse(item["relation_DateTime"].ToString()) : DateTime.MinValue,
                                next_RelationDateTime = item["next_RelationDateTime"] != null ?
                                    DateTime.Parse(item["next_RelationDateTime"].ToString()) : DateTime.MinValue,
                                relation_Node = item["relation_Node"]?.ToString(),
                                customer_ID = item["customer_ID"]?.ToString()
                            });
                        }
                    }
                    // 绑定到GridControl
                    var gridControl = userControl.MainGrid;
                    if (gridControl != null)
                    {
                        gridControl.DataSource = dataList;
                        var gridView = gridControl.MainView as GridView;
                        if (gridView != null)
                        {
                            // 设置列名
                            if (gridView.Columns["id"] != null)
                                gridView.Columns["id"].Caption = "ID";
                            if (gridView.Columns["relation_DateTime"] != null)
                            {
                                gridView.Columns["relation_DateTime"].Caption = "联系日期";
                                gridView.Columns["relation_DateTime"].DisplayFormat.FormatType = DevExpress.Utils.FormatType.DateTime;
                                gridView.Columns["relation_DateTime"].DisplayFormat.FormatString = "yyyy-MM-dd HH:mm:ss";
                            }
                            if (gridView.Columns["next_RelationDateTime"] != null)
                            {
                                gridView.Columns["next_RelationDateTime"].Caption = "下次联系日期";
                                gridView.Columns["next_RelationDateTime"].DisplayFormat.FormatType = DevExpress.Utils.FormatType.DateTime;
                                gridView.Columns["next_RelationDateTime"].DisplayFormat.FormatString = "yyyy-MM-dd HH:mm:ss";
                            }
                            if (gridView.Columns["relation_Node"] != null)
                                gridView.Columns["relation_Node"].Caption = "联系内容";
                            if (gridView.Columns["customer_ID"] != null)
                                gridView.Columns["customer_ID"].Caption = "客户ID";
                            // 表头加粗居中，内容居中
                            foreach (DevExpress.XtraGrid.Columns.GridColumn col in gridView.Columns)
                            {
                                col.AppearanceHeader.TextOptions.HAlignment = DevExpress.Utils.HorzAlignment.Center;
                                col.AppearanceHeader.Font = new System.Drawing.Font("Tahoma", 10, System.Drawing.FontStyle.Bold);
                                col.AppearanceCell.TextOptions.HAlignment = DevExpress.Utils.HorzAlignment.Center;
                            }
                            // 行号
                            gridView.IndicatorWidth = 40;
                            gridView.CustomDrawRowIndicator += (s, e) =>
                            {
                                if (e.Info.IsRowIndicator && e.RowHandle >= 0)
                                {
                                    e.Info.DisplayText = (e.RowHandle + 1).ToString();
                                }
                            };
                            // 滚动条
                            gridView.OptionsView.ColumnAutoWidth = false;
                            gridView.BestFitColumns();
                            gridView.OptionsView.ShowVerticalLines = DevExpress.Utils.DefaultBoolean.True;
                            gridView.OptionsView.ShowHorizontalLines = DevExpress.Utils.DefaultBoolean.True;
                            gridView.OptionsView.RowAutoHeight = true;
                        }
                    }
                    // 更新分页信息
                    userControl.lblPageInfo.Text = $"第{pageIndex}/{(GetTotalPages() == 0 ? 1 : GetTotalPages())}页 共{totalCount}条";
                }
                catch (Exception ex)
                {
                    XtraMessageBox.Show($"加载数据失败: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
        }
        
        /// <summary>
        /// 格式化网格视图
        /// </summary>
        private void FormatGridView(GridView gridView)
        {
            // 优化表格显示
            gridView.OptionsView.ColumnAutoWidth = false; // 允许自定义列宽
            gridView.BestFitColumns(); // 自动适应内容宽度
            
            // 启用滚动功能
            gridView.OptionsView.ShowVerticalLines = DevExpress.Utils.DefaultBoolean.True;
            gridView.OptionsView.ShowHorizontalLines = DevExpress.Utils.DefaultBoolean.True;
            gridView.OptionsView.RowAutoHeight = true;
            
            // 允许水平和垂直滚动
            gridView.OptionsView.EnableAppearanceEvenRow = true;
            gridView.OptionsView.EnableAppearanceOddRow = true;
            
            // 设置列样式
            foreach (DevExpress.XtraGrid.Columns.GridColumn col in gridView.Columns)
            {
                col.AppearanceHeader.TextOptions.HAlignment = DevExpress.Utils.HorzAlignment.Center; // 表头居中
                col.AppearanceHeader.Font = new System.Drawing.Font("Tahoma", 10, System.Drawing.FontStyle.Bold); // 表头加粗
                col.AppearanceCell.TextOptions.HAlignment = DevExpress.Utils.HorzAlignment.Center; // 内容居中
            }
            
            // 显示行号
            gridView.IndicatorWidth = 40;
            gridView.CustomDrawRowIndicator += (s, e) =>
            {
                if (e.Info.IsRowIndicator && e.RowHandle >= 0)
                {
                    e.Info.DisplayText = (e.RowHandle + 1).ToString();
                }
            };
        }

        public class AddRelationForm : XtraForm
        {
            public event Action RelationAdded;
            private TextEdit txtCode;
            private DateEdit dtRelationDate;
            private DateEdit dtNextRelationDate;
            private MemoEdit txtNode;
            private SimpleButton btnAdd, btnReset;
            private string customerId;

            public AddRelationForm(string customerId)
            {
                this.customerId = customerId;
                this.Width = 1000;
                this.Height = 800;
                this.StartPosition = FormStartPosition.CenterParent;
                this.FormBorderStyle = FormBorderStyle.FixedDialog;
                this.MaximizeBox = false;
                this.MinimizeBox = false;
                InitUI();
            }

            private void InitUI()
            {
                this.Text = "联系记录新增";
                this.BackColor = Color.White;

                // 标题
                var lblTitle = new Label()
                {
                    Text = "联系记录新增",
                    Font = new Font("微软雅黑", 28, FontStyle.Bold),
                    AutoSize = true,
                    TextAlign = ContentAlignment.MiddleCenter,
                    Location = new Point((this.Width - 400) / 2, 60)
                };

                int labelX = 200, inputX = 400, rowH = 80, startY = 180;

                // 客户ID
                var lblCustomerId = new Label() { Text = "客户ID：", Font = new Font("微软雅黑", 10), Location = new Point(labelX, startY), AutoSize = true, TextAlign = ContentAlignment.MiddleRight };
                var txtCustomerId = new TextEdit() { Text = customerId, Font = new Font("微软雅黑", 10), Location = new Point(inputX, startY - 10), Width = 400, Enabled = false };

                // 编码
                var lblCode = new Label() { Text = "编码：", Font = new Font("微软雅黑", 13), Location = new Point(labelX, startY + rowH), AutoSize = true, TextAlign = ContentAlignment.MiddleRight };
                txtCode = new TextEdit() { Text = "自动生成（无需自己添加）", Font = new Font("微软雅黑", 10), Location = new Point(inputX, startY + rowH - 10), Width = 400, Enabled = false };

                // 联系日期
                var lblRelationDate = new Label() { Text = "联系日期：", Font = new Font("微软雅黑", 13), Location = new Point(labelX, startY + rowH * 2), AutoSize = true, TextAlign = ContentAlignment.MiddleRight };
                dtRelationDate = new DateEdit() { Font = new Font("微软雅黑", 10), Location = new Point(inputX, startY + rowH * 2 - 10), Width = 400 };
                dtRelationDate.Properties.DisplayFormat.FormatString = "yyyy-MM-dd HH:mm:ss";
                dtRelationDate.Properties.DisplayFormat.FormatType = DevExpress.Utils.FormatType.DateTime;
                dtRelationDate.Properties.EditFormat.FormatString = "yyyy-MM-dd HH:mm:ss";
                dtRelationDate.Properties.EditFormat.FormatType = DevExpress.Utils.FormatType.DateTime;

                // 下次联系日期
                var lblNextRelationDate = new Label() { Text = "下次联系日期：", Font = new Font("微软雅黑", 10), Location = new Point(labelX, startY + rowH * 3), AutoSize = true, TextAlign = ContentAlignment.MiddleRight };
                dtNextRelationDate = new DateEdit() { Font = new Font("微软雅黑", 10), Location = new Point(inputX, startY + rowH * 3 - 10), Width = 400 };
                dtNextRelationDate.Properties.DisplayFormat.FormatString = "yyyy-MM-dd HH:mm:ss";
                dtNextRelationDate.Properties.DisplayFormat.FormatType = DevExpress.Utils.FormatType.DateTime;
                dtNextRelationDate.Properties.EditFormat.FormatString = "yyyy-MM-dd HH:mm:ss";
                dtNextRelationDate.Properties.EditFormat.FormatType = DevExpress.Utils.FormatType.DateTime;

                // 描述
                var lblNode = new Label() { Text = "描述：", Font = new Font("微软雅黑", 10), Location = new Point(labelX, startY + rowH * 4), AutoSize = true, TextAlign = ContentAlignment.MiddleRight };
                txtNode = new MemoEdit() { Font = new Font("微软雅黑", 10), Location = new Point(inputX, startY + rowH * 4 - 10), Width = 400, Height = 120 };

                // 按钮
                btnAdd = new SimpleButton() { Text = "添加", Font = new Font("微软雅黑", 10), Width = 140, Height = 50 };
                btnReset = new SimpleButton() { Text = "重置", Font = new Font("微软雅黑", 10), Width = 140, Height = 50 };
                btnAdd.Location = new Point(inputX + 30, startY + rowH * 5 + 20);
                btnReset.Location = new Point(inputX + 230, startY + rowH * 5 + 20);

                btnAdd.Click += async (s, e) => await AddRelation();
                btnReset.Click += (s, e) =>
                {
                    dtRelationDate.EditValue = null;
                    dtNextRelationDate.EditValue = null;
                    txtNode.Text = string.Empty;
                };

                this.Controls.Add(lblTitle);
                this.Controls.Add(lblCustomerId);
                this.Controls.Add(txtCustomerId);
                this.Controls.Add(lblCode);
                this.Controls.Add(txtCode);
                this.Controls.Add(lblRelationDate);
                this.Controls.Add(dtRelationDate);
                this.Controls.Add(lblNextRelationDate);
                this.Controls.Add(dtNextRelationDate);
                this.Controls.Add(lblNode);
                this.Controls.Add(txtNode);
                this.Controls.Add(btnAdd);
                this.Controls.Add(btnReset);
            }

            private async Task AddRelation()
            {
                if (dtRelationDate.EditValue == null || dtNextRelationDate.EditValue == null || string.IsNullOrWhiteSpace(txtNode.Text))
                {
                    XtraMessageBox.Show("请填写完整信息！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }
                var data = new
                {
                    id = "string",
                    relation_DateTime = ((DateTime)dtRelationDate.EditValue).ToString("yyyy-MM-ddTHH:mm:ss.fffZ"),
                    next_RelationDateTime = ((DateTime)dtNextRelationDate.EditValue).ToString("yyyy-MM-ddTHH:mm:ss.fffZ"),
                    relation_Node = txtNode.Text,
                    customer_ID = customerId
                };
                using (HttpClient client = new HttpClient())
                {
                    var content = new StringContent(Newtonsoft.Json.JsonConvert.SerializeObject(data), Encoding.UTF8, "application/json");
                    var resp = await client.PostAsync("http://localhost:5198/api/Record/AddRelation", content);
                    string json = await resp.Content.ReadAsStringAsync();
                    if (resp.IsSuccessStatusCode && json.Contains("添加成功"))
                    {
                        XtraMessageBox.Show("添加成功！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        RelationAdded?.Invoke();
                        this.Close();
                    }
                    else
                    {
                        XtraMessageBox.Show("添加失败！", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                }
            }
        }
    }
}